import needle from "needle";
import {encoder, urlConfig} from "../Config";
import Cookies from "js-cookie";

interface User {
    avatar?:string  | undefined, // 是一个文件名
    nickname?: string,
    password?: string,
    phone?: string,
    email?: string,
    account?: string,
    regDate?: string | Date,
    photo?: File
}

class UserController{
    user?: User | null = null;

    constructor() {
        const user = Cookies.get("currentLogUser");
        if (user) this.user=JSON.parse(user);
    }

    getUserInfo() {
        if (this.user === null) {
            return null;
        }
        return Object.assign({}, this.user);
    }

    async login(account: string, password: string) {
        /*user={
            nickname: "昵称",
            password: "password",
        }
        return user;*/

        const res = await needle("get",
            urlConfig.getUrlFor("/user/"+account)+"?password="+encoder.enc(password), )
        if (res.statusCode === 200) {
            this.user = res.body;
            if (this.user?.avatar)
                this.user.avatar = urlConfig.getPhotoUrlFor(this.user.account,  this.user.avatar);
            Cookies.set("currentLogUser", JSON.stringify(this.user));
            return Promise.resolve(this.user);
        }else return Promise.reject("登录失败");
    }

    async register(user: User) {
        if (user.password)
            user.password = encoder.enc(user.password);
        const res = await needle("post", urlConfig.getUrlFor("/user"), user,
            {multipart: true});
        if (res.statusCode === 200){
            return Promise.resolve(res.body);
        }else return Promise.reject("注册失败");
    }

    isLogged() {
        return this.user!=null;
    }

    exit() {
        this.user=null;
        Cookies.remove("currentLogUser");
    }
}

const  userController = new UserController();

export {userController};
export type { User };
